/*
 * File    : /src/views/mark/editor/components/PictureList/tools/base.js
 * Time    : 2021-09-10 13:35:55
 * Author  : Gray Snail
 * Version : 1.0
 * Contact : shtao2011@sina.com
 * License : Copyright (c) 2021 Gray Snail
 * Desc    : 2D 标注框在 Paperjs 的基础类
 *
 */

import paper from 'paper'
import { Annotation, FileType, AnnoType, ActionStat } from '../data/annotation'

function onMouseDrag(event) {
  if (event.event.buttons !== 1 || !event.target.selected) return

  const target = event.target
  target.draging = true
  target.position.x += event.delta.x
  target.position.y += event.delta.y
}

function onMouseUp(event) {
  const target = event.target
  console.log(event)
  if (target.draging && target.annotation) {
    target.annotation.pts = target.pts
    target.project?.onAnnoChange(target.annotation, { status: ActionStat.UPDATE })
  }
  target.draging = false
}

function onDoubleClick(event) {
  console.log(event)
  const target = event.target
  if (target.selected && target.annotation) {
    target.project?.updateProperty(target.annotation)
  }
}

/**
 * 2D 标注框基础类
 *
 */
export class BaseAnno extends paper.Group {
  /**
   * 数据
   */
  annotation = null

  constructor() {
    super()
    this.onDoubleClick = onDoubleClick
    // this.onMouseDrag = onMouseDrag
    // this.onMouseUp = onMouseUp
  }

  createAnnotation() {
    const project = this.project
    const anno = new Annotation(this.annoType, project.fileName, FileType.D2, project.mQaResultId)
    anno.pts = this.pts
    this.annotation = anno
    return anno
  }

  get annoType() {
    return AnnoType.UNKNOWN
  }

  set selected(val) {
    this.handlePoints.forEach((handlePath) => {
      handlePath.visible = val
      handlePath.selected = val
    })
    super.selected = val
    super.fullySelected = val
  }
  get selected() {
    return super.fullySelected
  }

  translate(delta) {
    super.translate(delta)
    this.triggerEvnet(ActionStat.UPDATE)
  }

  remove() {
    this.triggerEvnet(ActionStat.DELETE)
    super.remove()
  }

  triggerEvnet(status = ActionStat.UPDATE) {
    if (this.annotation) {
      console.log(status)
      this.annotation.pts = this.pts
      this.annotation.status = status
      this.project?.onAnnoChange(this.annotation)
    }
  }
}

export class BaseTool extends paper.Tool {
  get imageSize() {
    return paper.project.layers.mainLayer.rasterLayer.bounds
  }

  get project() {
    return paper.project
  }

  get layer() {
    return paper.project.activeLayer
  }

  get selectedItem() {
    return paper.project.selectedItem
  }

  set selectedItem(val) {
    const old = paper.project.selectedItem
    if (old === val) {
      return
    }
    paper.project.selectedItem = val
    paper.project?.onSelectedChange(val?.annotation || null)
  }
}
